package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/employee")
@Slf4j //日志注解
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @Param employee 封装用户名和密码
     * @Param session 会话域对象
     */
    @PostMapping("/login")
    public R<Employee> login(HttpSession session, @RequestBody Employee employee) {
        //把参数传递给Service
        R<Employee> result = employeeService.login(employee);
        //如果Code返回1则表示登录成功
        if (result.getCode() == 1) {
            //登录成功的标记
            session.setAttribute("employee", result.getData().getId());
        }
        return result;
    }

    /**
     * 退出登录
     *
     * @param session 会话域对象
     * @return
     */

    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.invalidate(); //清除session
        return R.success("退出成功");
    }

    /**
     * 添加员工
     * @param session
     * @param employee
     * @return
     */
  @PostMapping
    public R<String>  save(HttpSession session,@RequestBody Employee employee){
        //1.获取已登录的用户
      long empId=(long)session.getAttribute("employee");
      //补全信息
      employee.setCreateUser(empId);
      employee.setUpdateUser(empId);

      //把数据交给Service
     employeeService.save(employee);
     return R.success("退出成功");

  }


    /**
     * 员工列表分页
     * @param page 当前页
     * @param pageSize 页面大小
     * @param name 用户名字
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(Integer page,Integer pageSize,String name){
        Page<Employee> result = employeeService.findByPage( page,pageSize,name);
        return R.success(result);
    }


    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        //获取当前登录用户,修改更新者信息
    long empId = (long) session.getAttribute("employee");
    employee.setUpdateUser(empId);
        //把信息交给Service
        employeeService.update(employee);
        return R.success("修改成功");

    }

    /**
     * 根据Id查找员工
     */
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable("id") long id){
       R<Employee> result= employeeService.findById(id);
       return result;
    }


}